package edu.umn.msse.farside.FourH.web;

import edu.umn.msse.farside.FourH.domain.Volunteer;
import edu.umn.msse.farside.FourH.exceptions.DuplicateVolunteerException;
import edu.umn.msse.farside.FourH.exceptions.InvalidEmailException;
import edu.umn.msse.farside.FourH.services.VolunteerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * User: Farside
 * Date: Mar 16, 2009
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/createVolunteer")
public class CreateVolunteerController
{
    public VolunteerService volunteerService;

    @Autowired
    public void setVolunteerService(VolunteerService volunteerService)
    {
        this.volunteerService = volunteerService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String createVolunteerForm(Model model)
    {
        Volunteer volunteer = new Volunteer();
        model.addAttribute("volunteer", volunteer);
        return "createVolunteer";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String createVolunteer(@ModelAttribute(value="volunteer") Volunteer volunteer, BindingResult result)
    {
        // all volunteer fields are required
        if (StringUtils.isBlank(volunteer.getEmail())) {
            result.rejectValue("email", "required", "Required");  // property resource
        }
        if (StringUtils.isBlank(volunteer.getPassword())) {
            result.rejectValue("password", "required", "Required");
        }

        if(StringUtils.isBlank(volunteer.getFirstName())){
            result.rejectValue("firstName", "required", "Required");
        }

        if(StringUtils.isBlank(volunteer.getLastName())) {
            result.rejectValue("lastName", "required", "Required");
        }


        if (!result.hasErrors())
        {
            try
            {
                volunteerService.addVolunteer(volunteer);
            }
            catch (InvalidEmailException e)
            {
                result.rejectValue("email", "InvalidEmail", "Invalid Email format");  // property resource
            }
            catch (DuplicateVolunteerException e)
            {
                result.rejectValue("email", "DuplicateVolunteer", "You already have an acount!");  // property resource
            }
        }

        return result.hasErrors() ? "createVolunteer" : "redirect:/fourH/login";

    }
}
